<?php
namespace app\wxauth\controller;

use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\WxOpen;
use think\Controller;
use Wechat\Wxobjopen;

class Index extends Controller
{
    public function getauthopenid(){
        $param = request()->param();

        //获取授权为空时向微信发送请求
        if (!empty($param['mid'])) {
            $option = $this->options($param['mid']);

            $WxObj = new Wxobjopen($option);
            //获取授权openid
            $userinfo = $WxObj->getOpenoauthAccessToken();

            //获取授权为空时向微信发送请求
            if (empty($userinfo)) {
                $callback = request()->url(true);
                $url = $WxObj->getopenOauthCode($callback, '', 'snsapi_base');
                exit();
            }else{
                echo '1';
                $urls = base64_decode($param['url']).'/openid/'.$userinfo['openid'];
                header("Location:$urls");
            }
        }else{
            echo '错误';
        }
    }


    public function options($mid)
    {
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $mid;
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $users = $WxOpen->where($mab)->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }
}
